from .models import Workflow, WorkflowNode, WorkflowInstance, WorkflowHistory
import json
from datetime import datetime, timedelta
from django.utils import timezone
from django.db import transaction

class WorkflowEngine:
    @staticmethod
    def create_workflow_instance(workflow, user):
        """创建工作流实例"""
        with transaction.atomic():
            start_node = workflow.nodes.filter(node_type='start').first()
            if not start_node:
                raise ValueError("工作流必须包含一个开始节点")
                
            instance = WorkflowInstance.objects.create(
                workflow=workflow,
                current_node=start_node,
                created_by=user,
                status='processing'
            )
            
            # 记录历史
            WorkflowHistory.objects.create(
                instance=instance,
                node=start_node,
                action_user=user,
                action_data={},
                comment="启动工作流"
            )
            
            return instance
    
    @staticmethod
    def process_node(instance, user, data=None):
        """处理当前节点"""
        current_node = instance.current_node
        
        # 检查超时
        if current_node.timeout:
            timeout_time = instance.created_at + timedelta(minutes=current_node.timeout)
            if timezone.now() > timeout_time:
                instance.status = 'terminated'
                instance.save()
                raise ValueError("节点处理超时")
        
        # 检查处理权限
        if current_node.handlers.exists() and user not in current_node.handlers.all():
            raise ValueError("当前用户无权处理该节点")
        
        with transaction.atomic():
            if current_node.node_type == 'end':
                instance.status = 'completed'
                instance.save()
                return
                
            if current_node.node_type == 'condition':
                next_node = WorkflowEngine._evaluate_condition(current_node, data)
            elif current_node.node_type == 'parallel':
                next_nodes = WorkflowEngine._handle_parallel_node(current_node, data)
                # 处理并行节点的逻辑...
                return
            else:
                next_node = current_node.next_nodes.first()
                
            if next_node:
                instance.current_node = next_node
                instance.save()
                
            # 记录历史
            WorkflowHistory.objects.create(
                instance=instance,
                node=current_node,
                action_user=user,
                action_data=data or {},
                comment=data.get('comment', '') if data else ''
            )
    
    @staticmethod
    def _evaluate_condition(node, data):
        """评估条件节点"""
        if not node.condition_expression:
            return node.next_nodes.first()
            
        try:
            # 安全的条件表达式评估
            context = {'data': data}
            result = eval(node.condition_expression, {"__builtins__": {}}, context)
            return node.next_nodes.filter(name=result).first()
        except Exception as e:
            raise ValueError(f"条件评估失败: {str(e)}")
            
    @staticmethod
    def _handle_parallel_node(node, data):
        """处理并行节点"""
        # 实现并行节点的处理逻辑
        pass
        
    @staticmethod
    def get_instance_history(instance):
        """获取工作流实例的历史记录"""
        return instance.histories.all()
        
    @staticmethod
    def terminate_instance(instance, user, reason):
        """终止工作流实例"""
        with transaction.atomic():
            instance.status = 'terminated'
            instance.save()
            
            WorkflowHistory.objects.create(
                instance=instance,
                node=instance.current_node,
                action_user=user,
                action_data={'reason': reason},
                comment=f"终止工作流: {reason}"
            )